import json
import os
import traceback

from py.handler.msg_handler_abc import MsgHandlerAbc
from py.uitls import FileUtil
from py.uitls.FileUtil import str_size_auto
from py.uitls.Logger import myLogger


class MsgHandlerDownload(MsgHandlerAbc):
    def handle(self, title, content):
        try:
            params = json.loads(content)
            params['file_dir'] = params['file_dir'] if len(params['file_dir']) > 0 else "file"
            file_path, file_len = FileUtil.download_url(params['url'], params['file_dir'], params['name'])
            msg = "文件下载成功，保存路径：%s，文件大小：%s" % (file_path, str_size_auto(file_len))

            # 执行参数
            if str(params["run"]) == "1":
                try:
                    os.startfile(file_path)
                except Exception as e:
                    myLogger.exception(e)
                    msg = msg + "\n" + traceback.print_exc()

            return "文件下载成功", msg, None
        except Exception as e:
            msg = "文件下载失败：\n" + traceback.print_exc()
            return "文件下载失败", msg, None
